/**
 * 构建脚本 - 带环境校验
 * 确保构建环境与运行环境一致
 */
'use strict';

// 获取环境变量
const buildEnv = process.env.REACT_APP_ENV;
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const chalk = require('chalk') || { red: (text) => text, green: (text) => text, yellow: (text) => text };

// 环境映射
const ENV_MAP = {
  'development': '开发',
  'production': '生产'
};

console.log(`🔨 开始构建，当前环境: ${ENV_MAP[buildEnv] || buildEnv}环境 (${buildEnv})`);

try {
  // 使用execSync替代spawnSync以确保构建过程可以显示进度
  console.log('正在执行构建，请稍候...');
  execSync('react-scripts build', { stdio: 'inherit' });
  
  // 构建成功后，保存环境信息
  const buildDir = path.resolve(process.cwd(), 'build');
  
  // 确保build目录存在
  if (!fs.existsSync(buildDir)) {
    fs.mkdirSync(buildDir, { recursive: true });
  }
  
  const buildInfoPath = path.resolve(buildDir, 'env-info.json');
  
  // 将环境信息写入构建目录
  fs.writeFileSync(
    buildInfoPath,
    JSON.stringify({ 
      buildEnv, 
      buildTime: new Date().toISOString(),
      envName: ENV_MAP[buildEnv] || buildEnv
    }, null, 2),
    'utf8'
  );
  
  console.log(chalk.green(`✅ 应用构建完成 - ${ENV_MAP[buildEnv] || buildEnv}环境 (${buildEnv})`));
  console.log(`环境信息已写入: ${buildInfoPath}`);
} catch (error) {
  console.error(chalk.red('❌ 构建失败:'));
  console.error(error);
  process.exit(1);
} 